<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card shadow="hover">
      <el-row :gutter="20">
        <!-- 左边输入框 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable  @clear="getQueryUserList">
            <el-button slot="append" icon="el-icon-search" @click="getQueryUserList"></el-button>
           </el-input>
        </el-col>
        <!-- 右边button -->
        <el-col :span="6">
          <el-button type="primary" round @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table
        :data="userList"
        style="width: 100%"
        border stripe>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="用户名" ></el-table-column>
        <el-table-column prop="mobile" label="电话" ></el-table-column>
        <el-table-column prop="role_name" label="角色" ></el-table-column>
        <el-table-column prop="email" label="邮箱" ></el-table-column>
        <el-table-column prop="mg_state" label="状态" >
          <!-- 使用作用域插槽来渲染开关 -->
          <!-- 拿到tabale的每一行数据,在父级作用域渲染出来 -->
          <template v-slot:default="{row}">
            <!-- 转换开关  监听swicth开关事件 change ,保存state到数据库-->
            <el-switch @change="userStateChange(row)" v-model="row.mg_state" active-color="#13ce66" inactive-color="#ff4949"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" >
          <!-- 使用作用域插槽来渲染操作列 -->
          <template v-slot:default="{row}">
            <el-button-group>
              <!-- 修改 -->
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="editUserMessage(row.id)"></el-button>
              <!-- 删除 -->
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteUser(row.id)"></el-button>
              <!-- 分配 -->
              <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
                <el-button type="warning" icon="el-icon-setting" size="mini" @click="assignRole(row)"></el-button>
              </el-tooltip>
              <span v-show="false">{{row.id}}</span>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页模块 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="50%" @close="addDialogClose">
      <!-- 主要部分 -->
      <el-form :model="addFormData" :rules="formRules" ref="ruleFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addFormData.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="addFormData.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addFormData.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input  v-model="addFormData.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!--对话框 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="userAdd">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加修改用户对话框 -->
    <el-dialog
      title="修改信息"
      :visible.sync="editDialogVisible"
      width="50%" @close="editDialogClose">
      <!-- 主要部分 -->
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input  v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input  v-model="editForm.mobile" ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input  v-model="editForm.email"></el-input>
        </el-form-item>
      </el-form>
      <!--对话框 底部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog
      title="提示"
      :visible.sync="assignRoleDialogVisible"
      width="40%"
      >
      <p>当前用户：{{userInfo.userName}}</p>
      <p>当前角色：{{userInfo.role_name}}</p>
      <div>
        <el-select v-model="selectRole" placeholder="请选择">
          <el-option
            v-for="item in rolesList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id">
          </el-option>
        </el-select>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="assignRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {userMessageList,ChangeUserState, userMessageListeUserState,addUsers,userMessageById,editUserInfo,deleteUserInfo} from '../../networks/home'
import {getRolesList,assignUserRoleReq} from '../../networks/power'
export default {
  name:'Users',
  data() {
    //定义校验手机号的正则
    var checkMobile=(rule,value,callback)=>{
       var regMobile=/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/
      if (regMobile.test(value)){
        return callback();
      }else{
        callback(new Error('请输入合法的手机号'));
      }
    }
    //验证email的正则
    var checkEmail=(rule,value,callback)=>{
      var regEmail=/^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])/
      if (regEmail.test(value)){
        return callback();
      }else{
        callback(new Error('请输入合法的邮箱'))
      }
    }
    return {
      // 用户信息参数
      queryInfo:{
        query:'',
        // 当前页 
        pagenum:1,
        //当前每页显示多少条数据
        pagesize:2
      },
      total:0,
      userList:[],
      //控制对话框的显示与隐藏
      dialogVisible:false,
      //控制修改对话的显示与隐藏
      editDialogVisible:false,
      // 对话框中表单的数据对象
      addFormData:{
        username:'',
        password:'',
        email:'',
        mobile:'',
      },
      //绑定的规则对象
      formRules:{
        username:[ 
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }],
        password:[ 
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 5, max: 10, message: '长度在 5 到 10 个字符', trigger: 'blur' }],
        email:[ 
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator:checkEmail, trigger: 'blur' }],
        mobile:[ 
          { required: true, message: '请输入电话', trigger: 'blur' },
          {validator:checkMobile, trigger: 'blur' }],

        
      },
      //修改用户信息表单的数据，通过id请求得到
      editForm:{},
      //修改信息的验证规则对象
      editFormRules:{
        username:[ 
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }],
        email:[ 
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator:checkEmail, trigger: 'blur' }],
        mobile:[ 
          { required: true, message: '请输入电话', trigger: 'blur' },
          {validator:checkMobile, trigger: 'blur' }]
      },
      // 控制分配角色对话框的显示隐藏
      assignRoleDialogVisible:false,
      // 需要被分配角色的用户信息
      userInfo:{},
      //角色列表
      rolesList:[],
      //保存已经选择的角色id
      selectRole:''

    }
  },
  created() {
    userMessageList(this.queryInfo).then(res=>{
      // 获取不成功,弹出消息提示
      if(res.meta.status !==200) return this.$message.error(res.meta.mes);
      //获取成功保存数据
      this.total=res.data.total;
      this.userList=res.data.users;
      // console.log(this.total);
      // console.log(this.userList);
      
    })
  },
  methods: {
    //每页多少条,监听每页共有多少条的改变,拿到设置的每页条数
    handleSizeChange(pageSizes){
      // console.log(pageSizes);
      // 改变queryInfo里得pagesize,重新发起请求
      this.queryInfo.pagesize=pageSizes;
      userMessageList(this.queryInfo).then(res=>{
        // console.log("重新请求",res);
        // 保存修改得userlist和total;
        this.total=res.data.total;
        this.userList=res.data.users;
      });
    },
    //监听页码值得改变
    handleCurrentChange(newPage){
      console.log(newPage);
      // 给pagenum赋值重新发起数据请求
      this.queryInfo.pagenum=newPage;
      userMessageList(this.queryInfo).then(res=>{
        // 保存修改得userlist和total;
        this.total=res.data.total;
        this.userList=res.data.users;
      })

    },
    //监听用户状态得改变
    userStateChange(userInfo){
      // console.log("userinfo",userInfo);
      // 保存状态到数据库
      ChangeUserState(`users/${userInfo.id}/state/${userInfo.mg_state}`).then(res=>{
        // console.log("保存状态",res);
        if(res.meta.status!==200){
          userInfo.mg_state=this.userInfo.mg_state;
          return this.$message.error("更新用户状态失败");
        }else{
          return this.$message.success("更新用户状态成功")
        }
      })
    },
    //监听搜索按钮的点击，然后根据当前输入框的value双向绑定到query,根据query的改变发送请求
    getQueryUserList(){
      userMessageList(this.queryInfo).then(res=>{
        if(res.meta.status !==200) return this.$message.error(res.meta.mes);
        //获取成功保存数据
        this.total=res.data.total;
        this.userList=res.data.users;
      });
    },
    //监听对话框关闭，然后重置表单
    addDialogClose(){
      this.$refs.ruleFormRef.resetFields();
    },
    //监听对话框确定按钮的点击，验证通过后发起添加请求
    userAdd(){
      // validate传入回调，否则返回promise valid boolean
      this.$refs.ruleFormRef.validate(valid=>{
        if(!valid) return;
        //添加用户请求
        addUsers(this.addFormData).then(res=>{
          //指向vuecomponent
          console.log("adduser的this",this);
          if(res.meta.status!==201){
            return this.$message.error('添加用户返回数据失败！');
          }else{
            //添加成功后更新数据列表，提示添加成功，关闭对话框
            userMessageList(this.queryInfo).then(res=>{
              // console.log("usermessagelist.then里面的",this);
              console.log(res);
              // 获取不成功,弹出消息提示
              if(res.meta.status !==200) return this.$message.error(res.meta.mes);
              //获取成功保存数据
              this.total=res.data.total;
              this.userList=res.data.users; 
            })
            this.$message.success("添加成功");
            //关闭对话框
            this.dialogVisible=false;
          }

        })
      })
    },
    //监听编辑按钮点击，显示对话框，
    editUserMessage(id){
      this.editDialogVisible=true;
      console.log(id);
      //拿到id根据id查询用户信息
      userMessageById(`users/${id}`).then(res=>{
        console.log("id",res);
        if(res.meta.status!==200) return this.$message.error('查询失败')
        //将请求的数据保存起来
        this.editForm=res.data;
        console.log(this.editForm);
      })
    },
    // 监听修改信息对话框，关闭后重置对话表单数据
    editDialogClose(){
      this.$refs.editFormRef.resetFields()
      
    },
    //监听确定的点击事件，然后预验证
    editUserInfo(){
      this.$refs.editFormRef.validate(valid=>{
        if(!valid) return;
        //与验证通过，发送请求修改数据 put 注意封装的请求使用data接收参数
        console.log(this.editForm,"editForm");
        editUserInfo('users/'+this.editForm.id,
          {email:this.editForm.email,mobile:this.editForm.mobile}).then(res=>{
            // console.log(res,"更新的form");
            if(res.meta.status!==200){
              return this.$message.error("更新用户信息失败！")
            }else{
              //关闭对话框，更新列表，通知用户更新成功
              //添加成功后更新数据列表，提示添加成功，关闭对话框
              userMessageList(this.queryInfo).then(res=>{
              // 获取不成功,弹出消息提示
                if(res.meta.status !==200) return this.$message.error(res.meta.mes);
                //获取成功保存数据
                this.total=res.data.total;
                this.userList=res.data.users; 
              });
              this.$message.success("更新用户信息成功！");
              //关闭对话框
              this.editDialogVisible=false;
            }
          });
          
      })
    },
    //监听操作里面的删除按钮，点击删除弹出消息提示
    deleteUser(id){
      console.log(id);
      const result =this.$confirm('此操作将永久删除用户信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'});
      result.then(res=>{
        // res为confirm
        //删除用户信息，根据id
        console.log(res);
        deleteUserInfo('users/'+id).then(res=>{
          console.log(res,"deldata");
          if(res.meta.status!==200){
            return this.$message.error("删除失败！");
          }else{
            //更新数据
            userMessageList(this.queryInfo).then(res=>{
              // 获取不成功,弹出消息提示
              console.log(res,"删除");
              if(res.meta.status !==200) return this.$message.error(res.meta.mes);
                //获取成功保存数据
              this.total=res.data.total;
              this.userList=res.data.users; 
              });
              //提示成功，然后更新列表
            this.$message.success("删除成功!");
          }
        })
      }).catch(err=>{
        console.log(err);
        return this.$message.info("取消删除！");
        // err为cancel
      })

    },
    //监听操作里面的分配角色按钮
    assignRole(userInfo){
      //显示对话框之前，要请求所有角色的列表
      getRolesList().then(res=>{
        console.log("getRolesList",res);
        if(res.meta.status!==200) return this.$message.error(res.meta.msg);
        //存储所有角色列表
        this.rolesList=res.data;
        
      })
      //触发点击，弹出对话框
      this.assignRoleDialogVisible=true;
      this.userInfo=userInfo;
    },
    saveRoleInfo(){
      //发送保存角色的请求
      console.log(this.userInfo);
      console.log(this.userInfo.role_name);
      assignUserRoleReq(`users/${this.userInfo.id}}/role`,{rid:this.selectRole}).then(res=>{
        console.log(res,"assignUserRoleReq");
      })

    }
  },
}
</script>
<style scoped>
.el-breadcrumb{
  margin-bottom: 10px;
}
</style>